package com.zs.propertymanage.service.impl.impl;

import com.zs.propertymanage.dataObj.DTO;
import com.zs.propertymanage.dataObj.R;
import com.zs.propertymanage.dataObj.entity.Message;
import com.zs.propertymanage.dataObj.entity.PatrolPlan;
import com.zs.propertymanage.dataObj.entity.PatrolTask;
import com.zs.propertymanage.mapper.MessageMapper;
import com.zs.propertymanage.mapper.PatrolMapper;
import com.zs.propertymanage.service.impl.PatrolService;
import com.zs.propertymanage.websocket.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class PatrolServiceImpl implements PatrolService {

    @Autowired
    private PatrolMapper patrolMapper;
    @Autowired
    private MessageMapper messageMapper;

    // 巡查任务
    @Override
    public void generatePatrolTask(Integer frequency) {
        List<PatrolPlan> patrolPlanList = patrolMapper.getPatrolPlanListByFrequency(frequency);  // 获取指定频率下的任务计划列表
        patrolPlanList.forEach(patrolPlan -> {  // 遍历任务计划列表
            // 1. 查出该计划下的职责人员列表
            List<Map<String, String>> patrolPlanDuty = patrolMapper.getPatrolPlanDuty(patrolPlan.getId());
            // 2. 为其生成任务
            for (Map<String, String> map : patrolPlanDuty) {
                String dutyId = map.get("id");
                PatrolTask patrolTask = new PatrolTask();
                patrolTask.setId(UUID.randomUUID().toString());
                patrolTask.setPlanId(patrolPlan.getId());
                patrolTask.setEmployeeId(dutyId);
                patrolTask.setCreateTime(LocalDateTime.now());
                int result = patrolMapper.addPatrolTask(patrolTask);
                // 3. 消息通知
                if (result > 0) {
                    // websocket消息通知客户端
                    Message message = new Message(
                            UUID.randomUUID().toString(),
                            "新的巡查任务",
                            LocalDateTime.now(),
                            patrolPlan.getName() + "-" + patrolPlan.getContent(),
                            Message.TYPE_EMPLOYEE,
                            dutyId,
                            Message.TYPE_SYSTEM,
                            Message.ID_SYSTEM
                    );
                    messageMapper.addMessage(message);
                    WebSocketService.sendTextMessage(dutyId, "您有一条新的巡查任务~");    // 人员id改为了uuid，具有唯一性，不需要附加身份了
                }
            }
        });

    }

    @Override
    public R getPatrolTask(String search, Integer currentPage, Integer pageSize) {
        Integer start = (currentPage - 1) * pageSize;
        List<PatrolTask> patrolTaskList = patrolMapper.getPatrolTask(search, start, pageSize);
        Integer total = patrolMapper.getPatrolTaskCount(search);
        return total > 0 ? R.ok("获取巡查任务列表成功", new DTO<>(patrolTaskList, total)) : R.error("未查询到巡查任务");
    }

    @Override
    public R switchTaskCloseStatus(String id) {
        PatrolTask patrolTask = patrolMapper.getPatrolTaskById(id);
        patrolTask.setCloseStatus(patrolTask.getCloseStatus().equals(PatrolTask.CLOSE_STATUS_OPEN) ? PatrolTask.CLOSE_STATUS_CLOSE : PatrolTask.CLOSE_STATUS_OPEN);
        int result = patrolMapper.updatePatrolTask(patrolTask);
        return result > 0 ? R.ok("修改任务开关状态成功") : R.error("修改任务开关状态失败");
    }

    @Override
    public R getPatrolTaskByEmployeeId(String employeeId, String search, Integer currentPage, Integer pageSize) {
        List<PatrolTask> patrolTaskList = patrolMapper.getPatrolTaskByEmployeeId(employeeId, search, (currentPage - 1) * pageSize, pageSize);
        Integer total = patrolMapper.getPatrolTaskCountByEmployeeId(employeeId, search);
        return total > 0 ? R.ok("获取员工巡查任务列表成功", new DTO<>(patrolTaskList, total)) : R.error("未查询到员工巡查任务");
    }

    @Override
    public R handleTask(String taskId, String handleRemark) {
        PatrolTask patrolTask = patrolMapper.getPatrolTaskById(taskId);
        patrolTask.setHandleRemark(handleRemark);
        patrolTask.setHandleTime(LocalDateTime.now());
        patrolTask.setCompleteStatus(PatrolTask.COMPLETE_STATUS_COMPLETE);
        int result = patrolMapper.updatePatrolTask(patrolTask);
        return result > 0 ? R.ok("处理任务成功") : R.error("处理任务失败");
    }

    // 巡查计划
    @Override
    public R getPatrolPlan(String search, Integer currentPage, Integer pageSize) {
        Integer start = (currentPage - 1) * pageSize;
        List<PatrolPlan> patrolPlanList = patrolMapper.getPatrolPlan(search, start, pageSize);
        Integer total = patrolMapper.getPatrolPlanCount(search);
        return total > 0 ? R.ok("获取巡查计划列表成功", new DTO<>(patrolPlanList, total)) : R.error("未查询到巡查计划");
    }

    @Override
    public R addPatrolPlan(PatrolPlan patrolPlan) {
        String ppid = UUID.randomUUID().toString();
        patrolPlan.setId(ppid);

        int result1 = patrolMapper.addPatrolPlan(patrolPlan);
        if (result1 == 0)
            return R.error("添加巡查计划失败");

        List<Map<String, String>> dutyList = new ArrayList<>();
        for (String duty : patrolPlan.getDutyArr()) {
            Map<String, String> dutyMap = new HashMap<>();
            dutyMap.put("id", UUID.randomUUID().toString());
            dutyMap.put("ppid", ppid);
            dutyMap.put("eid", duty);
            dutyList.add(dutyMap);
        }
        int result2 = patrolMapper.setPatrolPlanDuty(dutyList);
        return result2 > 0 ? R.ok("添加巡查计划成功") : R.error("添加巡查计划时，配置职责人员失败");
    }

    @Override
    public R deletePatrolPlan(String id) {
        // 先删除巡查计划对应的巡查人员
        patrolMapper.deletePatrolPlanDuty(id);
        // 再删除巡查计划
        int result2 = patrolMapper.deletePatrolPlan(id);
        return result2 > 0 ? R.ok("删除巡查计划成功") : R.error("删除巡查计划失败");
    }

    @Override
    public R updatePatrolPlan(PatrolPlan patrolPlan) {
        // 先删除巡查计划对应的巡查人员
        patrolMapper.deletePatrolPlanDuty(patrolPlan.getId());
        // 再更新巡查计划
        int result2 = patrolMapper.updatePatrolPlan(patrolPlan);
        if (result2 == 0)
            return R.error("更新巡查计划失败");
        // 最后重新添加巡查人员
        if (patrolPlan.getDutyArr() == null || patrolPlan.getDutyArr().length == 0)
            return R.ok("更新巡查计划成功");    // 无职责人员时，直接返回更新成功

        List<Map<String, String>> dutyList = new ArrayList<>();
        for (String duty : patrolPlan.getDutyArr()) {
            Map<String, String> dutyMap = new HashMap<>();
            dutyMap.put("id", UUID.randomUUID().toString());
            dutyMap.put("ppid", patrolPlan.getId());
            dutyMap.put("eid", duty);
            dutyList.add(dutyMap);
        }
        int result3 = patrolMapper.setPatrolPlanDuty(dutyList);
        return result3 > 0 ? R.ok("更新巡查计划成功") : R.error("更新巡查计划时，配置职责人员失败");
    }

    @Override
    public R getPatrolPlanDuty(String planId) {
        List<Map<String, String>> dutyList = patrolMapper.getPatrolPlanDuty(planId);
        return dutyList == null ? R.error("未查询到巡查计划职责人员") : R.ok("获取巡查计划职责人员成功", dutyList);
    }
}
